import 'dart:io';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../services/theme_service.dart';

/// 全局应用背景组件
/// 用于在整个应用中显示背景图片或渐变色
class AppBackground extends ConsumerWidget {
  final Widget child;

  const AppBackground({Key? key, required this.child}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final themeConfig = ref.watch(appThemeConfigProvider);

    return Stack(
      fit: StackFit.expand,
      children: [
        // 背景层
        if (themeConfig.themeType == AppThemeType.custom &&
            themeConfig.backgroundImagePath != null)
          // 自定义背景图片
          Positioned.fill(
            child: Opacity(
              opacity: themeConfig.backgroundOpacity,
              child: _buildBackgroundImage(
                themeConfig.backgroundImagePath!,
                themeConfig.backgroundAlignment ?? Alignment.center,
              ),
            ),
          )
        else
          // 渐变背景色（用于预设主题）
          Positioned.fill(
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    ...themeConfig.gradientColors.map(
                      (color) => color.withOpacity(0.1),
                    ),
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
              ),
            ),
          ),

        // 内容层
        child,
      ],
    );
  }

  /// 构建背景图片组件
  Widget _buildBackgroundImage(String imagePath, Alignment alignment) {
    if (kIsWeb && imagePath.startsWith('web://')) {
      // Web平台：从SharedPreferences中读取图片数据
      return FutureBuilder<SharedPreferences>(
        future: SharedPreferences.getInstance(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox.shrink();
          }

          final prefs = snapshot.data!;
          final webImagePath = imagePath.substring(6); // 去掉'web://'前缀
          final imageData = prefs.getString(webImagePath);

          if (imageData == null) {
            return const SizedBox.shrink();
          }

          try {
            final imageBytes = Uint8List.fromList(imageData.codeUnits);
            return Image.memory(
              imageBytes,
              fit: BoxFit.cover,
              alignment: alignment,
            );
          } catch (e) {
            print('Web平台：加载背景图片失败: $e');
            return const SizedBox.shrink();
          }
        },
      );
    } else {
      // 移动平台：直接从文件加载图片
      return Image.file(
        File(imagePath),
        fit: BoxFit.cover,
        alignment: alignment,
      );
    }
  }
}
